package com.suxii.service;

import com.suxii.handler.*;
import com.suxii.pojo.ChatMsg;
import com.suxii.procotol.ChatCodec;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class ChatService {

    @Value("${netty.port}")
    private int port;

    //private StateHandler STATE_HANDLER=new StateHandler(); //用户在线状态
    //private ChatHandler CHAT_HANDLER=new ChatHandler(); //单人聊天
    //private LoginHandler LOGIN_HANDLER=new LoginHandler(); //登录
    //private ChatCodec CHAT_CODEC=new ChatCodec(); //自定义编解码器

    @Autowired
    private LoginHandler LOGIN_HANDLER; //登录

    @Autowired
    private StateHandler STATE_HANDLER; //用户在线状态

    @Autowired
    private ChatHandler CHAT_HANDLER; //单人聊天

    //@Autowired
    //private ChatCodec CHAT_CODEC; //自定义编解码器


    public void chat(){
        log.info("chat...");

        NioEventLoopGroup boss = new NioEventLoopGroup(1);
        NioEventLoopGroup woker = new NioEventLoopGroup();

        try {
            ServerBootstrap sb = new ServerBootstrap();
            sb.channel(NioServerSocketChannel.class);
            sb.group(boss,woker);
            sb.childOption(ChannelOption.SO_KEEPALIVE,true);//客户端长连接
            sb.childHandler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    p.addLast(new ChatCodec());
                    //p.addLast(LOGIN_HANDLER);
                    // 读事件超时时间
                    p.addLast(new IdleStateHandler(30,0,0));
                    // 心跳机制
                    p.addLast(new PingHandler());
                    p.addLast(STATE_HANDLER);
                    p.addLast(CHAT_HANDLER);

                }
            });
            ChannelFuture future = sb.bind(port).sync();

            // 阻塞，等待所有事件都处理完成，关闭
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            log.info("异常信息为:{}",e);
        } finally {
            woker.shutdownGracefully();
            boss.shutdownGracefully();
            log.info("服务器已关闭");
        }

    }

}
